<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>文章管理</title>
	<meta name="decorator" content="default"/>
	<script type="text/javascript">
		$(document).ready(function() {
            if($("#link").val()){
                $('#linkBody').show();
                $('#url').attr("checked", true);
            }
			$("#title").focus();
			$("#inputForm").validate({
				submitHandler: function(form){
                    // if ($("#categoryId").val()==""){
                    //     $("#categoryName").focus();
                    //     top.$.jBox.tip('请选择归属栏目','warning');
                    // // }else if (CKEDITOR.instances.content.getData()=="" && $("#link").val().trim()==""){
                    // //     top.$.jBox.tip('请填写回答','warning');
					var flag = true;
					if($(".list").length == 0){
						top.$.jBox.tip('请新增最少一条问题','warning');
						flag = false;
					}
					if(!flag){
						return;
					}
					$(".titleInput").each(function(){
						if($(this).val() == ""){
							top.$.jBox.tip('标题不能为空','warning');
							flag = false
							return;
						}
					})
					if(!flag){
						return;
					}
					$(".optionInput").each(function(){
						if($(this).val() == ""){
							top.$.jBox.tip('选项不能为空','warning');
							flag = false
							return;
						}
					})
					if($("#startDate").val() == "" || $("#endDate").val() == ""){
						top.$.jBox.tip('起止时间不能为空','warning');
						flag = false
						return;
					}
					if(!flag){
						return;
					}
					//收集问卷数据
					var itemList = [];
					var item;
					var optionList;
					var option;
					var idx;
					$(".list").each(function(){
						item = {}
						optionList = [];
						$(this).find(".answer .optionDiv").each(function () {
							idx = $(this).attr("idx");
							if(!$(this).attr("key")){
								return true;
							}
							option = {}
							// if($(this).find('div span input:radio:checked').length != 0){
							// 	option["selected"] = 1;
							// }else{
							// 	option["selected"] = 0;
							// }
							option["name"] = $(this).attr("key");
							option["title"] = $(this).find(".optionInput").val();
							optionList.push(option);
						})

						item["sort"] = $(this).find(".sortTd").attr("sort");
						item["title"] = $(this).find(".titleTd	 .titleInput").val();
						item["id"] = $(this).find(".titleTd	 .titleInput").attr("questionId");
						item["optionStr"] = optionList;
						itemList.push(item);
					})
					console.log(itemList);
					$("#surveryObj").val(JSON.stringify(itemList));
					loading('正在提交，请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});
		});

		function addRow(list, idx, tpl, row){
			if(row){
				$(list).append(Mustache.render(tpl, {
					idx: idx, delBtn: true, row: row, child: row.options[0]
				}));
			}else{
				$(list).append(Mustache.render(tpl, {
					idx: idx, delBtn: true, row: row
				}));
			}

			$(list+idx).find("select").each(function(){
				$(this).val($(this).attr("data-value"));
			});
			// $(list+idx).find("input[type='checkbox'], input[type='radio']").each(function(){
			// 	debugger;
			// 	var	ss = $(this).attr("data-value").split(',');
			//
			// 	for (var i=0; i<ss.length; i++){
			// 		if($(this).val() == ss[i]){
			// 			$(this).attr("checked","checked");
			// 		}
			// 	}
			// });
		}

		function delRow(obj, prefix){
			// var id = $(prefix+"_id");
			// var delFlag = $(prefix+"_delFlag");
			// if (id.val() == ""){
				$(obj).parent().parent().remove();
				testDataChildRowIdx = testDataChildRowIdx - 1;
			// }else if(delFlag.val() == "0"){
			// 	delFlag.val("1");
			// 	$(obj).html("&divide;").attr("title", "撤销删除");
			// 	$(obj).parent().parent().addClass("error");
			// }else if(delFlag.val() == "1"){
			// 	delFlag.val("0");
			// 	$(obj).html("&times;").attr("title", "删除");
			// 	$(obj).parent().parent().removeClass("error");
			// }
		}

		function addChildRow(list, idx, tpl, row){
			var key;
			if($(".answer"+idx +" .child").length == 0){
				key = "B";
			}else if($(".answer"+idx +" .child").length== 1){
				key = "C"
			}else if($(".answer"+idx +" .child").length == 2){
				key = "D"
				$(".init"+idx+" .new").hide();
			}else if($(".answer"+idx +" .child").length > 2){
				top.$.jBox.tip('选项已超过4条','warning');
				return false;
			}
			if($(".answer"+idx +" .child").length < 3){
				$(".answer"+idx).append(Mustache.render(tpl, {
					idx: idx, delBtn: true, row: row, key:key
				}));
				$(list+idx).find("select").each(function(){
					$(this).val($(this).attr("data-value"));
				});
				$(list+idx).find("input[type='checkbox'], input[type='radio']").each(function(){
					var ss = $(this).attr("data-value").split(',');
					for (var i=0; i<ss.length; i++){
						if($(this).val() == ss[i]){
							$(this).attr("checked","checked");
						}
					}
				});
			}
		}

		function delChildRow(obj, idx){
			$(obj).parent().parent().remove();
			if($(".answer"+idx +" .child").length < 3) {
				$(".init" + idx + " .new").show();
			}
		}

		function changeRadio(obj) {
			debugger;
			if($(obj).attr("checked")){
				$(obj).attr("checked","checked");
			}else{
				$(obj).removeAttr("checked");
			}
		}
	</script>


</head>
<body>
	<ul class="nav nav-tabs">
		<li><a href="${ctx}/cms/survery/">问卷列表</a></li>
		<li class="active"><a href="<c:url value='${fns:getAdminPath()}/cms/survery/form?id=${survery.id}}'></c:url>">问卷
			<shiro:hasPermission name="cms:survery:edit">${not empty survery.id?'修改':'添加'}
			</shiro:hasPermission><shiro:lacksPermission name="cms:survery:edit">查看</shiro:lacksPermission></a></li>
	</ul><br/>
	<form:form id="inputForm" modelAttribute="survery" action="${ctx}/cms/survery/save" method="post" class="form-horizontal">
		<form:hidden path="id"/>
		<sys:message content="${message}"/>
		<input type="hidden" id="surveryObj" name="surveryObj"/>

		<div class="control-group">
			<label class="control-label">权重:</label>
			<div class="controls">
				<form:input path="weight" htmlEscape="false" maxlength="200" class="input-mini required digits"/>&nbsp;
				<span>
					<input id="weightTop" type="checkbox" onclick="$('#weight').val(this.checked?'999':'0')"><label for="weightTop">置顶</label>
				</span>
					<%--				&nbsp;过期时间：--%>
					<%--				<input id="weightDate" name="weightDate" type="text" readonly="readonly" maxlength="20" class="input-small Wdate"--%>
					<%--					value="<fmt:formatDate value="${article.weightDate}" pattern="yyyy-MM-dd"/>"--%>
					<%--					onclick="WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:true});"/>--%>
					<%--				<span class="help-inline">数值越大排序越靠前，过期时间可为空，过期后取消置顶。</span>--%>
				<span class="help-inline">数值越大排序越靠前</span>
			</div>
		</div>

		<div class="control-group">
			<label class="control-label">标题:</label>
			<div class="controls">
				<form:input path="title" htmlEscape="false" maxlength="200" class="input-xxlarge  required"/>
			</div>
		</div>

		<div class="control-group">
			<label class="control-label">问卷：</label>
			<div class="controls">
				<table id="contentTable" class="table table-striped table-bordered table-condensed">
					<thead>
					<tr>
						<th class="hide"></th>
						<th >序号</th>
						<th style="width: 30%">题目</th>
						<th style="width: 60%">选项</th>
						<shiro:hasPermission name="cms:survery:edit"><th style="width:5%">&nbsp;</th></shiro:hasPermission>
					</tr>
					</thead>
					<tbody id="testDataChildList">
					</tbody>
					<shiro:hasPermission name="cms:survery:edit"><tfoot>
					<tr><td colspan="4"><a href="javascript:" onclick="addRow('#testDataChildList', testDataChildRowIdx, testDataChildTpl);testDataChildRowIdx = testDataChildRowIdx + 1;" class="btn">新增</a></td></tr>
					</tfoot></shiro:hasPermission>
				</table>

<%--				<input class="option option{{idx}}" name="option{{idx}}" onclick="changeRadio(this)" type="radio" value=""/>--%>
				<script type="text/template" id="testDataChildTpl">//<!--
						<tr id="testDataChildList{{idx}}" class="list">
							<td class="sortTd" sort="{{idx}}">
								{{idx}}
							</td>
							<td class="titleTd">
								<input style="width:350px" id="testDataChildList{{idx}}_name" name="testDataChildList[{{idx}}].name" type="text" value="{{row.title}}" questionId = "{{row.id}}" maxlength="100" class="input-small titleInput"/>
							</td>
							<td class="answer{{idx}} answer" index={{idx}}>
								<div class="init{{idx}} optionDiv" key="A" style=" height:30px; float:left; width:100%">
									<div style="width:10%;float:left;line-height:30px;height:30px;text-align:center">
										<span>A:</span>
									</div>
									<div style="float:left;">
										<input id="testDataChildList{{idx}}_remarks" name="testDataChildList[{{idx}}].remarks" type="text" value="{{child.title}}" maxlength="255" class="input-small optionInput"/>
									</div>
									<shiro:hasPermission name="cms:survery:edit">
									<div style="margin-left:5px;float:left;width:20%" class="new">
										<a href="javascript:" onclick="addChildRow('.answer{{idx}}', {{idx}}, testDataChildChildTpl);" class="btn">新增选项</a>
									</div>
									</shiro:hasPermission>
								</div>
							</td>
							<shiro:hasPermission name="cms:survery:edit">
							<td class="text-center">
								{{#delBtn}}<span class="close" onclick="delRow(this, '#testDataChildList{{idx}}')" title="删除">&times;</span>{{/delBtn}}
							</td>
							</shiro:hasPermission>
						</tr>
						//-->
				</script>
				<script type="text/template" id="testDataChildChildTpl">//<!--
					<div class="child optionDiv" key="{{key}}" style=" height:30px; float:left; width:100%; margin-top:5px">
						<div style="width:10%;float:left;line-height:30px;height:30px;text-align:center">
							<span>{{key}}:</span>
						</div>
						<div style="float:left" class="optionDiv">
							<input id="testDataChildList{{idx}}_remarks" name="testDataChildList[{{idx}}].remarks"  type="text" value="{{row.title}}" maxlength="255" class="input-small optionInput"/>
						</div>
						<shiro:hasPermission name="cms:survery:edit">
						<div style="margin-left:5%;float:left;width:5%">
							{{#delBtn}}<span class="close" onclick="delChildRow(this, {{idx}})" title="删除">&times;</span>{{/delBtn}}
						</div>
						</shiro:hasPermission>
					</div>

					//-->
				</script>
				<script type="text/javascript">
					var testDataChildRowIdx = 0, testDataChildTpl = $("#testDataChildTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
					var testDataChildChildTpl = $("#testDataChildChildTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
					var testDataChildChildRowIdx = 1;
					$(document).ready(function() {
						var data = ${fns:toJson(survery.questionList)};
						<%--var data = ${survery.questionList};--%>
						for (var i=0; i<data.length; i++){
							addRow('#testDataChildList', testDataChildRowIdx, testDataChildTpl, data[i]);
							testDataChildRowIdx = testDataChildRowIdx + 1;

							for(var n=1; n<data[i].options.length; n++){
								addChildRow('.answer', i, testDataChildChildTpl, data[i].options[n])
								// testDataChildChildRowIdx = testDataChildChildRowIdx + 1;
							}

						}
					});
				</script>
			</div>
		</div>
<%--		<div class="control-group">--%>
<%--			<label class="control-label">摘要:</label>--%>
<%--			<div class="controls">--%>
<%--				<form:textarea path="description" htmlEscape="false" rows="4" maxlength="200" class="input-xxlarge"/>--%>
<%--			</div>--%>
<%--		</div>--%>
<%--		<div class="control-group">--%>
<%--			<label class="control-label">缩略图:</label>--%>
<%--			<div class="controls">--%>
<%--                <input type="hidden" id="image" name="image" value="${article.imageSrc}" />--%>
<%--				<sys:ckfinder input="image" type="thumb" uploadPath="/cms/article" selectMultiple="false"/>--%>
<%--			</div>--%>
<%--		</div>--%>


<%--		<div class="control-group">--%>
<%--			<label class="control-label">回答:</label>--%>
<%--			<div class="controls">--%>
<%--				<form:textarea id="content" htmlEscape="true" path="content" rows="4" maxlength="200" class="input-xxlarge"/>--%>
<%--				<sys:ckeditor replace="content" uploadPath="/cms/question" />--%>
<%--			</div>--%>
<%--		</div>--%>
<%--		<div class="control-group">--%>
<%--			<label class="control-label">来源:</label>--%>
<%--			<div class="controls">--%>
<%--				<form:input path="articleData.copyfrom" htmlEscape="false" maxlength="200" class="input-xlarge"/>--%>
<%--			</div>--%>
<%--		</div>--%>
<%--		<div class="control-group">--%>
<%--			<label class="control-label">相关文章:</label>--%>
<%--			<div class="controls">--%>
<%--				<form:hidden id="articleDataRelation" path="articleData.relation" htmlEscape="false" maxlength="200" class="input-xlarge"/>--%>
<%--				<ol id="articleSelectList"></ol>--%>
<%--				<a id="relationButton" href="javascript:" class="btn">添加相关</a>--%>
<%--				<script type="text/javascript">--%>
<%--					var articleSelect = [];--%>
<%--					function articleSelectAddOrDel(id,title){--%>
<%--						var isExtents = false, index = 0;--%>
<%--						for (var i=0; i<articleSelect.length; i++){--%>
<%--							if (articleSelect[i][0]==id){--%>
<%--								isExtents = true;--%>
<%--								index = i;--%>
<%--							}--%>
<%--						}--%>
<%--						if(isExtents){--%>
<%--							articleSelect.splice(index,1);--%>
<%--						}else{--%>
<%--							articleSelect.push([id,title]);--%>
<%--						}--%>
<%--						articleSelectRefresh();--%>
<%--					}--%>
<%--					function articleSelectRefresh(){--%>
<%--						$("#articleDataRelation").val("");--%>
<%--						$("#articleSelectList").children().remove();--%>
<%--						for (var i=0; i<articleSelect.length; i++){--%>
<%--							$("#articleSelectList").append("<li>"+articleSelect[i][1]+"&nbsp;&nbsp;<a href=\"javascript:\" onclick=\"articleSelectAddOrDel('"+articleSelect[i][0]+"','"+articleSelect[i][1]+"');\">×</a></li>");--%>
<%--							$("#articleDataRelation").val($("#articleDataRelation").val()+articleSelect[i][0]+",");--%>
<%--						}--%>
<%--					}--%>
<%--					$.getJSON("${ctx}/cms/article/findByIds",{ids:$("#articleDataRelation").val()},function(data){--%>
<%--						for (var i=0; i<data.length; i++){--%>
<%--							articleSelect.push([data[i][1],data[i][2]]);--%>
<%--						}--%>
<%--						articleSelectRefresh();--%>
<%--					});--%>
<%--					$("#relationButton").click(function(){--%>
<%--						top.$.jBox.open("iframe:${ctx}/cms/article/selectList?pageSize=8", "添加相关",$(top.document).width()-220,$(top.document).height()-180,{--%>
<%--							buttons:{"确定":true}, loaded:function(h){--%>
<%--								$(".jbox-content", top.document).css("overflow-y","hidden");--%>
<%--							}--%>
<%--						});--%>
<%--					});--%>
<%--				</script>--%>
<%--			</div>--%>
<%--		</div>--%>
<%--		<div class="control-group">--%>
<%--			<label class="control-label">是否允许评论:</label>--%>
<%--			<div class="controls">--%>
<%--				<form:radiobuttons path="articleData.allowComment" items="${fns:getDictList('yes_no')}" itemLabel="label" itemValue="value" htmlEscape="false"/>--%>
<%--			</div>--%>
<%--		</div>--%>
<%--		<div class="control-group">--%>
<%--			<label class="control-label">推荐位:</label>--%>
<%--			<div class="controls">--%>
<%--				<form:checkboxes path="posidList" items="${fns:getDictList('cms_posid')}" itemLabel="label" itemValue="value" htmlEscape="false"/>--%>
<%--			</div>--%>
<%--		</div>--%>
<%--		<div class="control-group">--%>
<%--			<label class="control-label">发布时间:</label>--%>
<%--			<div class="controls">--%>
<%--				<input id="createDate" name="createDate" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate"--%>
<%--					value="<fmt:formatDate value="${survery.createDate}" pattern="yyyy-MM-dd HH:mm:ss"/>"--%>
<%--					onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false});"/>--%>
<%--			</div>--%>
<%--		</div>--%>
		<div class="control-group">
			<label class="control-label">开始时间:</label>
			<div class="controls">
				<input id="startDate" name="startDate" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate"
					   value="<fmt:formatDate value="${survery.startDate}" pattern="yyyy-MM-dd HH:mm:ss"/>"
					   onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',
					   			isShowClear:false,
					   			maxDate:'#F{$dp.$D(\'endDate\')||\'%y-%M-%d\'}'});"
					   			class="required"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">结束时间:</label>
			<div class="controls">
				<input id="endDate" name="endDate" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate"
					   value="<fmt:formatDate value="${survery.endDate}" pattern="yyyy-MM-dd HH:mm:ss"/>"
					   onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',
					   			isShowClear:false,
					   			minDate:'#F{$dp.$D(\'startDate\')||\'%y-%M-%d\'}'});"
					   			class="required"/>
			</div>
		</div>
		<shiro:hasPermission name="cms:survery:audit">
			<div class="control-group">
				<label class="control-label">发布状态:</label>
				<div class="controls">
					<form:radiobuttons path="delFlag" items="${fns:getDictList('cms_del_flag')}" itemLabel="label" itemValue="value" htmlEscape="false" class="required"/>
					<span class="help-inline"></span>
				</div>
			</div>
		</shiro:hasPermission>
<%--		<shiro:hasPermission name="cms:category:edit">--%>
<%--            <div class="control-group">--%>
<%--                <label class="control-label">自定义内容视图:</label>--%>
<%--                <div class="controls">--%>
<%--                      <form:select path="customContentView" class="input-medium">--%>
<%--                          <form:option value="" label="默认视图"/>--%>
<%--                          <form:options items="${contentViewList}" htmlEscape="false"/>--%>
<%--                      </form:select>--%>
<%--                      <span class="help-inline">自定义内容视图名称必须以"${article_DEFAULT_TEMPLATE}"开始</span>--%>
<%--                </div>--%>
<%--            </div>--%>
<%--            <div class="control-group">--%>
<%--                <label class="control-label">自定义视图参数:</label>--%>
<%--                <div class="controls">--%>
<%--                      <form:input path="viewConfig" htmlEscape="true"/>--%>
<%--                      <span class="help-inline">视图参数例如: {count:2, title_show:"yes"}</span>--%>
<%--                </div>--%>
<%--            </div>--%>
<%--		</shiro:hasPermission>--%>
<%--		<c:if test="${not empty article.id}">--%>
<%--			<div class="control-group">--%>
<%--				<label class="control-label">查看评论:</label>--%>
<%--				<div class="controls">--%>
<%--					<input id="btnComment" class="btn" type="button" value="查看评论" onclick="viewComment('${ctx}/cms/comment/?module=article&contentId=${article.id}&status=0')"/>--%>
<%--					<script type="text/javascript">--%>
<%--						function viewComment(href){--%>
<%--							top.$.jBox.open('iframe:'+href,'查看评论',$(top.document).width()-220,$(top.document).height()-180,{--%>
<%--								buttons:{"关闭":true},--%>
<%--								loaded:function(h){--%>
<%--									$(".jbox-content", top.document).css("overflow-y","hidden");--%>
<%--									$(".nav,.form-actions,[class=btn]", h.find("iframe").contents()).hide();--%>
<%--									$("body", h.find("iframe").contents()).css("margin","10px");--%>
<%--								}--%>
<%--							});--%>
<%--							return false;--%>
<%--						}--%>
<%--					</script>--%>
<%--				</div>--%>
<%--			</div>--%>
<%--		</c:if>--%>
		<div class="form-actions">
			<shiro:hasPermission name="cms:survery:edit"><input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存"/>&nbsp;</shiro:hasPermission>
			<input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
		</div>
	</form:form>
</body>
</html>